#!usr/bin/env python3
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score,\
    classification_report, confusion_matrix

# 完整的pipeline
'''preparing data'''
files = ['knn_data.csv','nbayes_data.csv','dtree_data.csv']
for file in files:
    data = pd.read_csv(file,header=None)
    print(data.iloc[:,2].value_counts())
    X = data.iloc[:,:-1]
    y = data.iloc[:,-1]

    '''training the model'''
    C = 0.3 # SVM regularization parameter
    models = (svm.SVC(kernel='linear', C=C),
              svm.LinearSVC(C=C, max_iter=10000),
              svm.SVC(kernel='rbf', gamma=0.7, C=C),
              svm.SVC(kernel='poly', degree=7, gamma='auto', C=C))
    models = (clf.fit(X, y) for clf in models)

    def plot_contours(ax, clf, xx, yy, **params):
        '''prediction'''
        Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        out = ax.contourf(xx, yy, Z, **params)
        return out

    def make_meshgrid(x, y, h=0.02):
        x_min, x_max = x.min() - 0.1, x.max() + 0.1
        y_min, y_max = y.min() - 0.1, y.max() + 0.1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                             np.arange(y_min, y_max, h))
        return xx, yy

    '''visualization'''
    i = 1;plt.figure(i);i+=1
    titles = ('SVC with linear kernel',
              'LinearSVC (linear kernel)',
              'SVC with RBF kernel',
              'SVC with polynomial (degree 7) kernel')
    fig, sub = plt.subplots(2, 2,figsize=(10,8))
    plt.subplots_adjust(wspace=0.4, hspace=0.4)
    X0, X1 = X.iloc[:, 0], X.iloc[:, 1]
    xx, yy = make_meshgrid(X0, X1)
    for clf, title, ax in zip(models, titles, sub.flatten()):
        _ = plot_contours(ax, clf, xx, yy,
                      cmap=plt.cm.coolwarm, alpha=0.8)
        _ = ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
        _ = ax.set_xlim(xx.min(), xx.max())
        _ = ax.set_ylim(yy.min(), yy.max())
        _ = ax.set_title(title)
plt.show()
